﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XWG.JWBST.ProcessInterfaces;
using XWG.Framework.MSException;
using System.IO;
using System.Web;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using XWG.Framework.AuthUtility;
using System.Collections.Specialized;

namespace XWG.JWBST.KckpImageProcess
{
    /// <summary>
    /// 快处快赔基本信息上传
    /// </summary>
    public class Process : IProcess
    {
        public string ProcessData(StreamReader reader, HttpContext context)
        {
            HttpRequest request = context.Request;
            NameValueCollection headers = request.Headers;
            string name = DateTime.Now.ToString("yyyy-MM-dd");
            Stream inStream = null;
            string soundpath = null;
            //读取流
            inStream = request.InputStream;
            BufferedStream bufferStreamIn = null;
            string choose = null;
            XWG.JWBST.JWBSTEntity.TbBstFastprocessFile image = new JWBSTEntity.TbBstFastprocessFile();
            XWG.JWBST.JWBSTEntity.TbBstFastprocess fastinfo = new JWBSTEntity.TbBstFastprocess();
            image.Fileid = Guid.NewGuid().ToString();
            image.Fastlsh = context.Request.QueryString["LSH"].ToString();
            image.Filepicnum = context.Request.QueryString["BH"].ToString();
            string filename = image.Fastlsh + "_" + image.Filepicnum;


            ////判断事故流水号是否存在
            //if (XWG.JWBST.JWBSTBLL.TbBstFastprocessFileBLL.IsExistLSH(image.Fastlsh))
            //{
            if (image.Filepicnum != "Sound")
            {
                #region 图片存储
                var originalImage = System.Drawing.Image.FromStream(inStream);
                int originalWidth = originalImage.Width;    //原始图片的宽度
                int originalHeight = originalImage.Height;  //原始图片的高度
                //新建一个bmp图片
                System.Drawing.Image bitmap = new System.Drawing.Bitmap(originalWidth, originalHeight);

                //新建一个画板
                System.Drawing.Graphics graphic = System.Drawing.Graphics.FromImage(bitmap);

                //设置高质量查值法
                graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

                //设置高质量，低速度呈现平滑程度
                graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

                //清空画布并以透明背景色填充
                graphic.Clear(System.Drawing.Color.Transparent);

                //在指定位置并且按指定大小绘制原图片的指定部分
                graphic.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, originalWidth, originalHeight), new System.Drawing.Rectangle(0, 0, originalWidth, originalHeight), System.Drawing.GraphicsUnit.Pixel);


                try
                {
                    CreateFile file = new CreateFile();
                    file.CreateDir("\\Kckp\\KckpImage\\" + name + "\\");
                    bitmap.Save(HttpContext.Current.Server.MapPath("\\Kckp\\KckpImage\\") + name + "\\" + filename + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                    choose = "pic";
                    image.Upfile = "/Kckp/KckpImage/" + name + "/" + filename + ".jpg";

                    File.AppendAllText(HttpContext.Current.Server.MapPath("") + "\\log.txt", "数据库文件路径：" + name + "\r\n" + "______________________________________\r\n");
                }
                catch (Exception ex)
                {
                    choose = "图片存储失败";
                    MSEx.DealErr(ex, "");
                }
                finally
                {
                    originalImage.Dispose();
                    bitmap.Dispose();
                    graphic.Dispose();
                }
                #endregion
            }
            else
            {
                #region 声音存储
                bufferStreamIn = new BufferedStream(inStream);
                if (inStream.Length > 0)
                {
                    string houzhui = string.Empty;
                    CreateFile file = new CreateFile();
                    file.CreateDir("\\Kckp\\KckpImage\\" + name + "\\");

                    FileStream fs = new FileStream(HttpContext.Current.Server.MapPath("\\Kckp\\KckpImage\\") + name + "\\" + filename + ".amr", FileMode.Create);
                    BinaryWriter bw = new BinaryWriter(fs);
                    bw.Write(SetStreamToBytes(inStream));
                    bw.Close();
                    fs.Close();
                    choose = "sound";
                    //soundpath = (HttpContext.Current.Server.MapPath("\\Kckp\\KckpImage\\")).ToString() + filename + "\\" + file;
                    soundpath = "/Kckp/KckpImage/" + name + "/" + filename + ".amr";
                    File.AppendAllText(HttpContext.Current.Server.MapPath("") + "\\log.txt", "数据库文件路径：" + name + "\r\n" + "______________________________________\r\n");
                }
                #endregion
            }

            if (choose == "pic")
            {
                ResultModel re = new ResultModel();
                re = XWG.JWBST.JWBSTBLL.TbBstFastprocessFileBLL.Insert(image, "", false);
                if (re.ISSucceed)
                {
                    return "第" + image.Filepicnum + "张图片上传成功";
                }
                else
                {
                    return "第" + image.Filepicnum + "张图片上传失败";
                }
            }

            else if (choose == "sound")
            {
                //存储声音路径
                if (XWG.JWBST.JWBSTBLL.TbBstFastprocessBLL.UpSound(soundpath, image.Fastlsh))
                {
                    return "音频上传成功";
                }
                else
                {
                    return "音频上传失败";
                }
            }
            else
            {
                return choose;
            }
            //}
            //else
            //{
            //    return "该案件流水号不存在";
            //}
        }

        /// <summary>
        /// Stream to bytes
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public byte[] SetStreamToBytes(Stream stream)
        {
            try
            {
                byte[] bytes = new byte[stream.Length];
                stream.Read(bytes, 0, bytes.Length);
                // 设置当前流的位置为流的开始 
                stream.Seek(0, SeekOrigin.Begin);
                return bytes;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

    }
}
